import fileTypes from '../constants/fileTypes.js'
import { renderSize } from '@/utils/file'
import { getFileListSign, getDelSign } from '@exploit/api/file'

export const basePath = 'static_file'

/**
 * 获取basePath目录下的文件列表
 * @param {String} prefix 前缀，必须以/结尾
 * @returns
 */
export function getFileList(prefix = '/') {
  if (!/\/$/.test(prefix)) {
    console.error('前缀必须以/结尾')
    return
  }
  try {
    const cos = new COS({
      getAuthorization: async function(_, callback) {
        callback({
          Authorization: (await getFileListSign()).data.Authorization
        })
      }
    })

    return new Promise((resolve, reject) => {
      const pre = `${ basePath }${ prefix }`
      const preLen = pre.split('/').filter(item => item).length

      cos.getBucket({
        Bucket: 'aha-public-1301319986', /* 必须 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Prefix: pre, /* 非必须 */
      }, function(err, data) {
        if (err) {
          reject(err)
        } else {
          const files = data.Contents.filter(file => {
            const keys = file.Key.split('/').filter(item => item)

            return keys.length === preLen + 1
          })

          files.sort((a, b) => new Date(a.LastModified) - new Date(b.LastModified))
          resolve(files.map(file => {
            const type = fileTypes.find(item => item.reg.test(file.Key))

            return {
              key: file.Key,
              size: renderSize(file.Size),
              ...type
            }
          }))
        }
      })
    })
  } catch (err) {
    return Promise.reject(err)
  }
}

/**
 * 删除文件
 * @param {String} key 文件key值
 */
export function delFile(key) {
  try {
    const cos = new COS({
      getAuthorization: async function(_, callback) {
        callback({
          Authorization: (await getDelSign(key)).data.Authorization
        })
      }
    })

    return new Promise((resolve, reject) => {
      cos.deleteObject({
        Bucket: 'aha-public-1301319986',
        Region: 'ap-shanghai',
        Key: key
      }, function(err, data) {
        if (err) {
          reject(err)
        } else {
          resolve(data)
        }
      })
    })
  } catch (err) {
    return Promise.reject(err)
  }
}

/**
 * 获取文件时间戳
 */
export function getFileTime() {
  const date = new Date()

  let str = ''

  str += date.getFullYear()
  str += date.getMonth() + 1 < 10 ? `0${ date.getMonth() + 1 }` : date.getMonth() + 1
  str += date.getDate() < 10 ? `0${ date.getDate() }` : date.getDate()
  str += date.getHours() < 10 ? `0${ date.getHours() }` : date.getHours()
  str += date.getMinutes() < 10 ? `0${ date.getMinutes() }` : date.getMinutes()
  str += date.getSeconds() < 10 ? `0${ date.getSeconds() }` : date.getSeconds()
  str += date.getMilliseconds()
  return str
}
